package com.wlyy.his.service.ums.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlyy.his.ali.auth.AliMiniAuthUtil;
import com.wlyy.his.bean.common.dto.LoginDto;
import com.wlyy.his.common.util.RedisUtil;
import com.wlyy.his.ali.auth.AliAuthProperties;
import com.wlyy.his.entity.pc.Patient;
import com.wlyy.his.entity.pc.PatientCertificate;
import com.wlyy.his.entity.ums.*;
import com.wlyy.his.infrastructure.common.AuthCommon;
import com.wlyy.his.infrastructure.common.RequestUserInfo;
import com.wlyy.his.mapper.pc.PatientCertificateMapper;
import com.wlyy.his.mapper.pc.PatientMapper;
import com.wlyy.his.mapper.ums.*;
import com.wlyy.his.service.ums.IAccountService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 账户 服务实现类
 * </p>
 *
 * @author ZhouYanhui
 * @since 2021-08-31
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Resource
    private AccountMapper accountMapper;
    @Resource
    private AccountInfoMapper accountInfoMapper;
    @Resource
    private AccountOuthMapper accountOuthMapper;
    @Resource
    private CertificateMapper certificateMapper;
    @Resource
    private IdentityTypeMapper identityTypeMapper;
    @Resource
    private PatientMapper patientMapper;
    @Resource
    private PatientCertificateMapper patientCertificateMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private AliMiniAuthUtil aliMiniAuthUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String login(LoginDto loginDto) {
        String accountId = "";
        //用户端，支付宝授权登录
        if (1==loginDto.getRole() && 1==loginDto.getType()){
            //获取access_token
            AlipaySystemOauthTokenResponse response = aliMiniAuthUtil.getAccessToken(loginDto.getCode());
//            AlipaySystemOauthTokenResponse response = new AlipaySystemOauthTokenResponse();
//            response.setUserId("2088002921302748");
//            response.setAccessToken("authusrB9b2755dc80db496ea5da1fc6e4daaX74");
//            response.setRefreshToken("authusrB810273ebeedc40ecaceabdee68a5aA74");
            if(null!=response){
                AccountOuth aoExist = accountOuthMapper.selectOne(new QueryWrapper<AccountOuth>()
                        .eq("identity_type", 1)
                        .eq("identifier", response.getUserId()));
                if (null!=aoExist){
                    accountId = aoExist.getAccountId();
                    //更新access_token
                    aoExist.setCredential(response.getAccessToken());
                    aoExist.setCredentialExtra(response.getRefreshToken());
                    accountOuthMapper.updateById(aoExist);
                }else{
                    //获取用户的信息
                    AlipayUserInfoShareResponse userInfo = aliMiniAuthUtil.getUserInfo(response.getAccessToken());
//                    AlipayUserInfoShareResponse userInfo = new AlipayUserInfoShareResponse();
//                    userInfo.setAvatar("https://tfs.alipayobjects.com/images/partner/T1orpgXfJrXXXXXXXX");
//                    userInfo.setCertNo("330326198910151813");
//                    userInfo.setCertType("0");
//                    userInfo.setCity("杭州市");
//                    userInfo.setArea("滨江区");
//                    userInfo.setAddress("建设三路");
//                    userInfo.setGender("m");
//                    userInfo.setIsCertified("T");
//                    userInfo.setMobile("15727802745");
//                    userInfo.setNickName("书发");
//                    userInfo.setUserName("郑书发");
//                    userInfo.setProvince("浙江省");
//                    userInfo.setUserId("2088002921302748");

                    if (null!=userInfo){
                        String telephone = userInfo.getMobile();
                        //查询该用户是否已经创建
                        Account accountExist = accountMapper.selectOne(new QueryWrapper<Account>()
                                .eq("telephone",telephone)
                                .eq("role",1));
                        //  不存在就添加
                        if (null==accountExist){
                            //添加账户
                            Account account = new Account();
                            account.setTelephone(telephone);
                            account.setRole(1);
                            accountMapper.insert(account);

                            //添加账户具体的信息
                            //用户详细信息
                            AccountInfo accountInfo = new AccountInfo();
                            BeanUtil.copyProperties(userInfo,accountInfo);
                            accountInfo.setAccountId(account.getAccountId());
                            accountInfo.setName(userInfo.getUserName());
                            accountInfoMapper.insert(accountInfo);

                            //记录授权信息
                            AccountOuth accountOuth = new AccountOuth();
                            accountOuth.setAccountId(account.getAccountId());
                            accountOuth.setIdentityType(1);
                            accountOuth.setIdentifier(userInfo.getUserId());
                            accountOuth.setCredential(response.getAccessToken());
                            accountOuth.setCredentialExtra(response.getRefreshToken());
                            accountOuthMapper.insert(accountOuth);

                            //添加就诊人
                            Patient patient = new Patient();
                            patient.setVerified("T".equals(userInfo.getIsCertified())?1:0);
                            patient.setPhoneNumber(account.getTelephone());
                            patient.setIsUser(1);
                            BeanUtil.copyProperties(accountInfo,patient);
                            patientMapper.insert(patient);

                            //证件信息添加
                            //证件信息
                            if ("T".equals(userInfo.getIsCertified())){
                                //添加就诊人证件信息
                                PatientCertificate patientCertificate = new PatientCertificate();
                                patientCertificate.setCertExpiryDate(userInfo.getPersonCertExpiryDate());
                                patientCertificate.setCertNo(userInfo.getCertNo());
                                patientCertificate.setCertType(Integer.valueOf(userInfo.getCertNo()));
                                patientCertificate.setPatientId(patient.getPatientId());
                                patientCertificate.setVerified(1);
                                patientCertificateMapper.insert(patientCertificate);
                            }

                            accountId = account.getAccountId();
                        }
                    }
                }

            }

        }
        addIdentityType(accountId,loginDto.getType());
        return getToken(accountId);
    }


    /**
     * 记录登录方式
     * @param accountId 账号id
     * @param type 授权类型
     */
    private void addIdentityType(String accountId, Integer type){
        if (StringUtils.isNotBlank(accountId)){
            //记录登录方式
            IdentityType identityType = identityTypeMapper.selectOne(new QueryWrapper<IdentityType>()
                    .select("account_id")
                    .eq("account_id", accountId));
            if (null!=identityType){
                identityType.setIdentityType(type);
                identityType.setUpdateTime(LocalDateTime.now());
                identityTypeMapper.updateById(identityType);
            }else{
                IdentityType it = new IdentityType();
                it.setIdentityType(type);
                it.setAccountId(accountId);
                identityTypeMapper.insert(it);
            }
        }
    }


    /**
     *
     * 生成token 保存token
     * @param  accountId 账户Id
     * @return token
     */
    private String getToken(String accountId){
        //将用户信息存在缓存中
        if(StringUtils.isNotBlank(accountId)){
            String token = UUID.randomUUID().toString();
            boolean set = redisUtil.set(AuthCommon.CACHE_USER_REDIS_KEY + token, accountId, AuthCommon.TOKEN_CACHE_TIME);
            if (set){
                return token;
            }
        }
        return "";
    }
}


